package com.hpin.fansea.utils;


import android.annotation.TargetApi;
import android.app.ProgressDialog;
import android.content.Context;
import android.os.Build;
import android.widget.Toast;

import com.lidroid.xutils.HttpUtils;
import com.lidroid.xutils.exception.HttpException;
import com.lidroid.xutils.http.RequestParams;
import com.lidroid.xutils.http.ResponseInfo;
import com.lidroid.xutils.http.callback.RequestCallBack;
import com.lidroid.xutils.http.client.HttpRequest;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;

/**
 * 网络请求工具
 * Created by Aaron on 2015/7/16.
 */
public class HttpUtil {

    private HttpUtil() {

        httpUtils = new HttpUtils();
        httpUtils.configCurrentHttpCacheExpiry(0);
        httpUtils.configDefaultHttpCacheExpiry(0);
        httpUtils.configSoTimeout(10 * 10000);
        httpUtils.configTimeout(10 * 10000);
    }

    private static HttpUtil httpUtil = new HttpUtil();

    public static HttpUtil getInstance() {

        return httpUtil;
    }

    private HttpUtils httpUtils;

    /**
     * POST 请求
     *
     * @param message 提示信息
     * @param ctx     上下文对象
     * @param url     url地址
     * @param params  提交给服务器的json参数
     * @param success 成功的监听
     * @param fail    失败的监听
     */
    public void setPostRequest(String message, final Context ctx, String url, RequestParams params, final SuccessListener success, final FailListener fail) {


        if (!CommonUtils.isNetworkAvailable(ctx)) {
            Toast.makeText(ctx, "网络请求失败，请检查您的网络设置", Toast.LENGTH_LONG).show();
            return;
        }

        final ProgressDialog dialog = new ProgressDialog(ctx);

        dialog.setTitle(message);
        dialog.setMessage(Constant.WAIT);
        dialog.setCancelable(false);

        httpUtils.send(HttpRequest.HttpMethod.POST, url, params, new RequestCallBack<String>() {

            @TargetApi(Build.VERSION_CODES.JELLY_BEAN_MR1)
            @Override
            public void onStart() {
                super.onStart();

                if (ctx != null)
                    dialog.show();

            }

            @Override
            public void onSuccess(ResponseInfo<String> responseInfo) {

                if (dialog != null && dialog.isShowing())
                    dialog.dismiss();

                LogUtil.e("TAG", "返回的json======>" + responseInfo.result);

                if (success != null) {
                    success.setOnSuccessListener(responseInfo.result);
                }


            }

            @Override
            public void onFailure(HttpException e, String s) {
                if (dialog != null && dialog.isShowing())
                    dialog.dismiss();

                Toast.makeText(ctx, "请求数据失败!", Toast.LENGTH_SHORT).show();
                LogUtil.e("TAG", "fail=====>" + s);

                e.printStackTrace();

                if (fail != null) {
                    fail.setOnFailListener();
                }
            }
        });
    }

    /**
     * GET 请求 带 参数params
     *
     * @param message 提示信息
     * @param ctx     上下文对象
     * @param url     url地址
     * @param params  提交给服务器的json参数
     * @param success 成功的监听
     * @param fail    失败的监听
     */
    public void setGetRequest(String message, final Context ctx, String url, RequestParams params, final SuccessListener success, final FailListener fail) {


        if (!CommonUtils.isNetworkAvailable(ctx)) {
            Toast.makeText(ctx, "网络请求失败，请检查您的网络设置", Toast.LENGTH_LONG).show();
            return;
        }

        final ProgressDialog dialog = new ProgressDialog(ctx);

        dialog.setTitle(message);
        dialog.setMessage(Constant.WAIT);
        dialog.setCancelable(false);

        httpUtils.send(HttpRequest.HttpMethod.GET, url, params, new RequestCallBack<String>() {

            @TargetApi(Build.VERSION_CODES.JELLY_BEAN_MR1)
            @Override
            public void onStart() {
                super.onStart();

                if (ctx != null)
                    dialog.show();


            }

            @Override
            public void onSuccess(ResponseInfo<String> responseInfo) {

                if (dialog != null && dialog.isShowing())
                    dialog.dismiss();

                LogUtil.e("TAG", "返回的json======>" + responseInfo.result);

                if (success != null) {
                    success.setOnSuccessListener(responseInfo.result);
                }


            }

            @Override
            public void onFailure(HttpException e, String s) {
                if (dialog != null && dialog.isShowing())
                    dialog.dismiss();

                Toast.makeText(ctx, "请求数据失败!", Toast.LENGTH_SHORT).show();
                LogUtil.e("TAG", "fail=====>" + s);

                e.printStackTrace();

                if (fail != null) {
                    fail.setOnFailListener();
                }
            }
        });
    }

    /**
     * GET 请求
     *
     * @param message 提示信息
     * @param ctx     上下文对象
     * @param url     url地址
     * @param success 成功的监听
     * @param fail    失败的监听
     */
    public void setGetRequest(String message, final Context ctx, final String url, final SuccessListener success, final FailListener fail) {

        if (!CommonUtils.isNetworkAvailable(ctx)) {
            Toast.makeText(ctx, "网络请求失败，请检查您的网络设置", Toast.LENGTH_LONG).show();
            return;
        }

        final ProgressDialog dialog = new ProgressDialog(ctx);

        dialog.setTitle(message);
        dialog.setMessage(Constant.WAIT);
        dialog.setCancelable(false);

        httpUtils.send(HttpRequest.HttpMethod.GET, url, new RequestCallBack<String>() {

            @TargetApi(Build.VERSION_CODES.JELLY_BEAN_MR1)
            @Override
            public void onStart() {
                super.onStart();

                if (ctx != null)
                    dialog.show();

                LogUtil.e("TAG", "请求的json===>>>>" + url);

            }

            @Override
            public void onSuccess(ResponseInfo<String> responseInfo) {

                if (dialog != null && dialog.isShowing())
                    dialog.dismiss();

                LogUtil.e("TAG", "返回的json======>" + responseInfo.result);

                if (success != null) {
                    success.setOnSuccessListener(responseInfo.result);
                }

            }

            @Override
            public void onFailure(HttpException e, String s) {
                if (dialog != null && dialog.isShowing())
                    dialog.dismiss();

                Toast.makeText(ctx, "请求数据失败!", Toast.LENGTH_SHORT).show();
                LogUtil.e("TAG", "fail=====>" + s);

                e.printStackTrace();

                if (fail != null) {
                    fail.setOnFailListener();
                }
            }
        });

    }

    public interface SuccessListener {

        void setOnSuccessListener(String str);

    }


    public interface FailListener {

        void setOnFailListener();

    }

    /**
     * 上传图片
     */
    public String load(String URL, byte[] bytes) {

        String text = null;

        try {
            java.net.URL url = new URL(URL);

            HttpURLConnection uc = (HttpURLConnection) url.openConnection();
            uc.setRequestProperty(
                    "Accept",
                    "image/gif,   image/x-xbitmap,   image/jpeg,   image/pjpeg,   application/vnd.ms-excel,   " +
                            "application/vnd.ms-powerpoint,   application/msword,   application/x-shockwave-flash,   application/x-quickviewplus,   */*");
            uc.setRequestProperty("Accept-Language", "zh-cn");
            uc.setRequestProperty("Content-type",
                    "multipart/form-data;   boundary=---------------------------7d318fd100112");
            uc.setRequestProperty("Accept-Encoding", "gzip,   deflate");
            uc.setRequestProperty("User-Agent",
                    "Mozilla/4.0   (compatible;   MSIE   6.0;   Windows   NT   5.1)");
            uc.setRequestProperty("Connection", "Keep-Alive");
            uc.setDoOutput(true);
            uc.setRequestMethod("POST");
            //设置容许输出
            uc.setDoOutput(true);
            //不使用缓存
            uc.setUseCaches(false);
            //超时时间10秒
            uc.setConnectTimeout(10000);

            OutputStream out = uc.getOutputStream();
            out.write(bytes);
            out.flush();
            out.close();

            int code = uc.getResponseCode();
            String sCurrentLine = "";
            String sTotalString = "";
            if (code == 200) {
                java.io.InputStream is1 = uc.getInputStream();
                BufferedReader reader = new BufferedReader(
                        new InputStreamReader(is1));
                while ((sCurrentLine = reader.readLine()) != null)
                    if (sCurrentLine.length() > 0)
                        sTotalString = sTotalString + sCurrentLine.trim();
            }
            text = sTotalString;
            LogUtil.e("net", text);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return text;

    }

}
